﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data;
//using System.Web.Services.Protocols;
//using System.Data;

namespace SalaryChannel.Web
{
    /// <summary>
    /// DCWebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class DCWebService : System.Web.Services.WebService, IDisposable
    {

        private readonly string AccountID = "TS.GS.CHINAMOBILE";
        private readonly string PIN = "YANGCHAO@COBS";

        private Credentials _token = new Credentials() { AccountID = string.Empty, PIN = string.Empty };
        /// <summary>
        /// SOAP
        /// </summary>
        public Credentials Token
        {
            get
            {
                return _token;
            }
            set
            {
                _token = value;
            }
        }

         SalaryChannel.Web.DataClassesQueryDataContext context = new DataClassesQueryDataContext();

        [WebMethod]
        public int Login(string UserID, string Pwd)
        {
            try
            {
               
                var query = from p in context.UserInfor
                            where p.User_ID == UserID
                            where p.Password == Pwd
                            select p;
                if (query.Any())
                {
                    ///成功
                    return query.First().AdminLevel;
                        
                }
                else
                {
                    //用户名或密码不正确
                    return -2;
                }
            }
            catch (Exception e)
            {
                LogManager.Write(UserID+"--"+ HttpContext.Current.Request.UserHostAddress
                    +"-- 登录失败--"+  e.Message);
                return -3;//发生异常
            }
        }
        
        [WebMethod]
        //[SoapHeader("Token", Direction = SoapHeaderDirection.In)]
        public string GetUserInfor(string UserID)
        {
            try
            {
               
                //if (Token == null
                //    || Token.AccountID != this.AccountID
                //    || Token.PIN != this.PIN)
                //{
                //    //throw new Exception("非法的请求：" + this.AccountID + this.PIN + this.Context.Request.UserHostAddress);
                //}

                var query = from q in context.UserInfor
                            where q.User_ID == UserID
                            select q;
                string str = string.Format("用户名：{0}    登录局向: [{1}]{2}",
                    query.First().UserName, query.First().Channel_ID, query.First().Channel_Name);
                return str;
            }
            catch (Exception e)
            {
                
                LogManager.Write("查询用户信息失败：" + UserID+"--"+e.Message);
                return string.Empty;
            }
        }


        [WebMethod]
        //[SoapHeader("Token", Direction = SoapHeaderDirection.In)]
        public int ChangePwd(string UserID, string OldPwd, string NewPwd,bool isAdmin)
        {
            try
            {
                //if (Token == null
                //       || Token.AccountID != this.AccountID
                //       || Token.PIN != this.PIN)
                //{
                //    //throw new Exception("非法的请求：" + this.AccountID + this.PIN + this.Context.Request.UserHostAddress);
                //}
                if (isAdmin)
                {
                    var pwd = from q in context.UserInfor
                              where q.User_ID == UserID
                              select q;
                    if (!pwd.Any())
                    {
                        return 3;//用户不存在
                    }
                    pwd.First().Password = NewPwd;
                }
                else
                {
                    var query = from p in context.UserInfor
                                where p.User_ID == UserID
                                where p.Password == OldPwd
                                select p;

                    if (!query.Any())
                    {
                        //原密码不正确
                        return 1;
                    }
                    query.First().Password = NewPwd;
                }
                context.SubmitChanges();
                return 0;
            }
            catch (Exception e)
            {
                LogManager.Write("修改密码失败:" + UserID + "--" + e.Message + "--" + Context.Request.UserHostAddress);
                return 2;//发生异常
            }

        }

        [WebMethod]
        //[SoapHeader("Token", Direction = SoapHeaderDirection.In)]
        public List<PublicInfor> GetPublicInfor()
        {
            try
            {
                //if (Token == null
                //       || Token.AccountID != this.AccountID
                //       || Token.PIN != this.PIN)
                //{
                //    //throw new Exception("非法的请求：" + this.AccountID + this.PIN + this.Context.Request.UserHostAddress);
                //}
                DateTime now = DateTime.Now;
                var query = from p in context.PublicInfor
                            where now <= p.Expire_Date
                            where p.IsValid =='1'
                            orderby p.Create_Date descending
                            select p;

                return query.ToList<PublicInfor>();
            }
            catch (Exception ex)
            {
                LogManager.Write("获取公告信息失败:" + ex.Message + "--" + Context.Request.UserHostAddress);
                return new List<PublicInfor>();
            }

        }
        [WebMethod]
        //[SoapHeader("Token", Direction = SoapHeaderDirection.In)]
        public string ExposePublicInfor(int ID)
        {
            try
            {
                //if (Token == null
                //       || Token.AccountID != this.AccountID
                //       || Token.PIN != this.PIN)
                //{
                //    //throw new Exception("非法的请求：" + this.AccountID + this.PIN + this.Context.Request.UserHostAddress);
                //}
                var query = from p in context.PublicInfor
                            where p.ID == ID
                            select p;

                PublicInfor pi = query.First();
                pi.IsValid = '0';
                //context.PublicInfor.u(pi);
                context.SubmitChanges();
                return "true";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }



        [WebMethod]
        //[SoapHeader("Token", Direction = SoapHeaderDirection.In)]
        public string AddPublicInofr(string Body, string ExpireDate,string UserID)
        {
            try
            {
                //if (Token == null
                //       || Token.AccountID != this.AccountID
                //       || Token.PIN != this.PIN)
                //{
                //    //throw new Exception("非法的请求：" + this.AccountID + this.PIN + this.Context.Request.UserHostAddress);
                //}
                var query = from q in context.UserInfor
                            where q.User_ID == UserID
                            select q.UserName;


                PublicInfor pi = new PublicInfor();
                pi.Body = string.Format("{0} \r[{1}  {2}]",Body,query.First(),DateTime.Now.ToShortDateString());
                pi.Create_Date = DateTime.Now;
                pi.IsValid = '1';
                pi.Expire_Date = (DateTime)(new DateTimeConverter().ConvertFromString(ExpireDate));

                context.PublicInfor.InsertOnSubmit(pi);
                context.SubmitChanges();
                return "true";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

       

        [WebMethod]
        public List<UserInfor> QueryUserInfor(string UserID, string ChannelID)
        {
            try
            {
                if (string.IsNullOrEmpty(UserID))
                {
                    return (from q in context.UserInfor
                            where q.Channel_ID == ChannelID
                            select q).ToList<UserInfor>();
                }
                else if (string.IsNullOrEmpty(ChannelID))
                {
                    return (from p in context.UserInfor
                            where p.User_ID == UserID
                            select p).ToList<UserInfor>();
                }
                else
                {
                    return (from p in context.UserInfor
                            where p.User_ID == UserID
                            where p.Channel_ID == ChannelID
                            select p).ToList<UserInfor>();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("查询用户管理信息失败:" + UserID + "--" + ChannelID + "--" + ex.Message + "--" + Context.Request.UserHostAddress);
                return new List<UserInfor>();
            }
        }
        [WebMethod]
        public string DeleteUser(string UserID)
        {
            try
            {
                var query = from p in context.UserInfor
                            where p.User_ID == UserID
                            select p;
                if (query.Any())
                {
                    context.UserInfor.DeleteOnSubmit(query.First());
                }
                context.SubmitChanges();
                return "true";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        [WebMethod]
        public string AddUser(string UserID, string UserName, string ChannelID, string ChannelName,
            string Password, int Level)
        {
            try
            {

                UserInfor newUser = new UserInfor();
                newUser.User_ID = UserID;
                newUser.UserName = UserName;
                newUser.Channel_ID = ChannelID;
                newUser.Channel_Name = ChannelName;
                newUser.Password = Password;
                newUser.AdminLevel = Level;
                context.UserInfor.InsertOnSubmit(newUser);
                context.SubmitChanges();
                return "true";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        [WebMethod]
        public List<QueryLogTable> GetQueryLogTable(string StatisMon)
        {
            string sqlString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SalaryQueryConnectionString"].ConnectionString;

            using (SqlConnection sqlCon = new SqlConnection(sqlString))
            {
                
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = sqlCon;
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.CommandText = "QueryLogTable";
                    cmd.Parameters.Add(new SqlParameter("@StatisMon", StatisMon));

                    DataTable dt = new DataTable();
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);

                     List<QueryLogTable> result = new List<QueryLogTable>();
                     int ChannelTotal = 0;
                     int QueryTotal = 0;
                     int ValidTotal = 0;
                     float ValidPTotal = 0F; 
                    foreach (DataRow dr in dt.Rows)
                    {
                        QueryLogTable ql = new QueryLogTable
                        {
                            AreaName = dr["Area"].ToString(),
                            ChannelCount = int.Parse(dr["ChannelCount"].ToString()),
                            QueryCount =  int.Parse(dr["QueryCount"].ToString()),
                            ValidChannelCount =
                            int.Parse(dr["ValidCount"].ToString()),
                            ValidP =  string.Format("{0:P2}",float.Parse(dr["ValidPP"].ToString())) };
                        ChannelTotal += ql.ChannelCount;
                        QueryTotal += ql.QueryCount;
                        ValidTotal += ql.ValidChannelCount;
                      
                        result.Add(ql);
                       
                    }
                    ValidPTotal = (float)ValidTotal / (float)ChannelTotal;
                    result.Add(new QueryLogTable
                    {
                        AreaName = "总计",
                        ChannelCount = ChannelTotal,
                        QueryCount = QueryTotal,
                        ValidChannelCount = ValidTotal,
                        ValidP = string.Format("{0:P2}",ValidPTotal) 
                    });
                   
                    
                    return result;
                }
                catch (Exception ex)
                {
                    LogManager.Write("统计使用情况失败:" + StatisMon + "--" + ex.Message + "--" + Context.Request.UserHostAddress);
                    return new List<QueryLogTable>();
                }

            }
        }
     

    
        #region IDisposable 成员

        void IDisposable.Dispose()
        {
            context.Dispose();
            GC.SuppressFinalize(this);
        }

        #endregion
    }

    public class QueryLogTable
    {
        public string AreaName
        { get; set; }
        public int ChannelCount
        { get; set; }
        public int QueryCount
        { get; set; }
        public int ValidChannelCount
        {
            set;
            get;
        }
        public string ValidP
        {
            get;
            set;
        }
    }
}
#region old
//    private string sqlString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["sqlString"].ConnectionString;
//    private SqlService serviceIns;

//    private string currentUser = string.Empty;
//    public DCWebService()
//    {
//        serviceIns = SqlService.GetInstance(sqlString);
//    }
//    [WebMethod]
//    public string HelloWorld()
//    {
//        return "Hello World";
//    }

//    [WebMethod]
//    public bool Login(string id, string pwd)
//    {
//        try
//        {
//            bool result = serviceIns.Login(id, pwd);
//            if (result)
//            {
//                currentUser = id;
//            }
//            return result;
//        }
//        catch (Exception e)
//        {

//            LogManager.Write(e.Message);
//            return false;
//        }
//    }

//    [WebMethod]
//    public UserInfor GetCurrentUserInfor(string User_ID)
//    {
//        try
//        {
//            return serviceIns.GetUserInfor(User_ID);

//        }
//        catch (Exception e)
//        {

//            LogManager.Write(e.Message);
//            return null ;
//        }
//    }

//    [WebMethod]
//    public DataTable GetTaskInfor(string User_ID)
//    {
//        try
//        {
//            return serviceIns.GetTaskInfor(User_ID);

//        }
//        catch (Exception e)
//        {

//            LogManager.Write(e.Message);
//            return null;
//        }
//    }

//    [WebMethod]
//    public DataTable GetTableInfor(string User_ID)
//    {
//        try
//        {
//            return serviceIns.GetTableInfor(User_ID);

//        }
//        catch (Exception e)
//        {

//            LogManager.Write(e.Message);
//            return null;
//        }
//    }
//}
#endregion
